package com.zbec.mdrs.service;

import com.zbec.framework.core.service.SystemDictionaryService;
import com.zbec.framework.core.util.PageUtils;
import com.zbec.framework.core.vo.JqgridResponse;
import com.zbec.framework.core.vo.PageInfo;
import com.zbec.framework.security.service.SecurityService;
import com.zbec.mdrs.constants.Constants;
import com.zbec.mdrs.entity.RecordEntity;
import com.zbec.mdrs.entity.report.ReportConfig;
import com.zbec.mdrs.entity.report.ReportFile;
import com.zbec.mdrs.entity.report.ReportFileRel;
import com.zbec.mdrs.entity.report.ReportTask;
import com.zbec.mdrs.repository.jpa.ReportConfigDao;
import com.zbec.mdrs.repository.jpa.ReportFileDao;
import com.zbec.mdrs.repository.jpa.ReportFileRelDao;
import com.zbec.mdrs.repository.jpa.ReportTaskDao;
import com.zbec.mdrs.util.DateUtils;
import com.zbec.mdrs.util.ResourceUtils;
import com.zbec.mdrs.vo.ReportFileVo;
import com.zbec.mdrs.vo.TxtBeanMapping;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * Created by fxl on 2015/10/19.
 */
@Component
@Transactional
public class ReportFileService {
    @Autowired
    private ReportFileDao reportFileDao;

    @Autowired
    private ReportFileRelDao reportFileRelDao;

    @Autowired
    private ReportTaskDao reportTaskDao;

    @Autowired
    private SecurityService securityService;

    @Autowired
    private SystemDictionaryService systemDictionaryService;

    @Autowired
    private ReportConfigDao reportConfigDao;




    public JqgridResponse<ReportFileVo> findAllReportFile(PageInfo pageInfo) {
        Page<ReportFileVo>  reportFileVoPage= reportFileDao.findAllReportFile(PageUtils.buildPageRequest(pageInfo));
        packagingBean(reportFileVoPage.getContent());
        return PageUtils.buildResponse(reportFileVoPage, reportFileVoPage.getContent());
    }


    public JqgridResponse<ReportFileVo> findFileByTaskId(Long taskId,PageInfo pageInfo) {
        Page<ReportFileVo>  reportFileVoPage= reportFileDao.findReportFileByTaskId(taskId,PageUtils.buildPageRequest(pageInfo));
        packagingBean(reportFileVoPage.getContent());
        return PageUtils.buildResponse(reportFileVoPage, reportFileVoPage.getContent());
    }


    public void  packagingBean(List<ReportFileVo> list){
        for (int i = 0; i <list.size() ; i++) {
            ReportFileVo reportFileVo=list.get(i);
            reportFileVo.setBusinessTypeDesc(systemDictionaryService.getSystemDictionaryDesc(Constants.Constants_YWLX, reportFileVo.getBusinessType()));
        }
    }



    public Boolean generateFileByMonth(List list,String year,String month,TxtBeanMapping beanMapping,String path,String userIp) {

        List<ReportConfig> configList=reportConfigDao.findAll();
        String type="1";
        if(configList.size()>0){
            type=configList.get(0).getType();
        }
        Date ywDate = DateUtils.getDate(Integer.parseInt(year),Integer.parseInt(month),1);
        String ywMonth = DateUtils.convertDateToString(DateUtils.DATE_FORMAT_YYYYMMdd, DateUtils.getLastDayOfThisMonth(ywDate));
        ReportTask reportTask;

        List<ReportTask> taskList = reportTaskDao.findActiveReportTaskByYwMonthAndBizType(Integer.parseInt(year),Integer.parseInt(month),beanMapping.getBizKey(),Constants.REPORT_TASK_STATUS_VRY_CMP_REP_CMP);
        if(taskList!=null&&taskList.size()==0){
            reportTask = new ReportTask();
            reportTask.setBusinessMonth(DateUtils.getLastDayOfThisMonth(ywDate));
            reportTask.setBusinessType(beanMapping.getBizKey());
            reportTask.setReportTimes(1);
            reportTask.setStatus(Constants.REPORT_TASK_STATUS_GEN_CMP_REP);

        }else{
            reportTask =taskList.get(0);
            reportTask.setReportTimes(reportTask.getReportTimes()+1);
            reportTask.setStatus(Constants.REPORT_TASK_STATUS_GEN_CMP_RE_REP);
        }

        reportTaskDao.save(reportTask);

        int rt = reportTask.getReportTimes();
        String suffer="";
        if(type.equals("0")) {
            suffer=Constants.REPORT_FILE_EXTENSION;
        }else {
            suffer= Constants.REPORT_FILE_EXT_XLS;
        }
        String filename = Constants.BANK_CODE_F335+"_"+beanMapping.getBizKey()+"_"+ ywMonth+"_"+(rt<10?"0"+rt:rt)+suffer;
        File dir = new File(path+"/"+DateUtils.convertDateToString(DateUtils.DATE_FORMAT_YYYYMM, ywDate));
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String filepath = dir.getAbsolutePath()+"/"+filename;

        ReportFile reportFile = new ReportFile();
        reportFile.setFileName(filename);
        reportFile.setFileUrl(filepath);
        reportFile.setFileType(Constants.REPORT_FILE_TYPE_REPORT);
        reportFile.setReportDate(new Date());
        reportFile.setReportMan(this.securityService.getCurrentUser().getLoginName());
        reportFile.setTask(reportTask);
        reportFileDao.save(reportFile);
        reportTask.getFiles().add(reportFile);

        FileOutputStream fout = null;
        BufferedOutputStream buff=null;
        HSSFWorkbook wb=null;
        HSSFSheet sheet=null;
        HSSFRow row=null;
        HSSFCellStyle style=null;

        try {
            if(type.equals("0")){
                fout = new FileOutputStream(new File(filepath));
                buff = new BufferedOutputStream(fout);
            }else{
                // 第一步，创建一个webbook，对应一个Excel文件
                wb = new HSSFWorkbook();
                // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet

                sheet = wb.createSheet("文件");
                // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
                row = sheet.createRow((int) 0);
                // 第四步，创建单元格，并设置值表头 设置表头居中
                style = wb.createCellStyle();
                style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
            }




            Map columnMapping = beanMapping.getColumnMapping();
            String[] cls = new String[columnMapping.size()];

            int x=0;
            for (Iterator iterator = columnMapping.keySet().iterator(); iterator.hasNext();) {
                String key = (String) iterator.next();
                cls[x] = key;

                if(type.equals("0")) {
                    buff.write(key.getBytes());
                    if(x!=cls.length){
                        buff.write("\t".getBytes());
                    }
                }else{
                    HSSFCell cell = row.createCell(x);
                    cell.setCellValue(key);
                    cell.setCellStyle(style);
                }
                x++;
            }
            if(type.equals("0")) {
                 buff.write("\r\n".getBytes());
            }

            for(int j=0;j<list.size();j++){
                RecordEntity o = (RecordEntity) list.get(j);
                ReportFileRel rel = new ReportFileRel();
                rel.setFile(reportFile);
                rel.setRecordId(o.getId());
                rel.setLineNum(j+1);
                reportFileRelDao.save(rel);
                reportFile.getRels().add(rel);

                o.setReportStatus(Constants.REPORT_STATUS_LOCKED);
                if(type.equals("1")) {
                    row = sheet.createRow(j + 1);
                }
                for (int i = 0; i < cls.length; i++) {
                    String property = (String) columnMapping.get(cls[i]);
                    Object r = PropertyUtils.getProperty(o, property);
                    String value="";
                    if(r!=null){
                        if(r instanceof Date){
                            if(type.equals("0")) {
                                  buff.write((DateUtils.convertDateToString(DateUtils.DATE_FORMAT_YYYYMMdd, (Date) r)).getBytes());
                            }else{
                                value = DateUtils.convertDateToString(DateUtils.DATE_FORMAT_YYYYMMdd, (Date) r);
                            }
                        }else {
                            if(type.equals("0")) {

                                System.out.println("Value is ======="+wrappDesc(r, property));
                                System.out.println("GBK Value is ======="+wrappDesc(r, property).getBytes("GBK"));
                                System.out.println("UTF-8 Value is ======="+wrappDesc(r, property).getBytes("utf-8"));
                                String encoding = System.getProperty("file.encoding");
                                System.out.println(encoding);
                                buff.write(wrappDesc(r, property).getBytes());
                            }else{
                                value = r.toString();
                            }
                        }
                        if(type.equals("1")){
                            if (value!=null && !value.equals("null") && !value.equals("")) {
                                row.createCell(i).setCellValue(value);
                            } else {
                                row.createCell(i).setCellValue("");
                            }
                        }
                    }
                    if(type.equals("0") && i!=cls.length-1){
                        buff.write("\t".getBytes());
                    }

                }
                if(type.equals("0") && j!=list.size()-1){
                    buff.write("\r\n".getBytes());
                }
            }
            if(type.equals("0")){
                buff.flush();
                buff.close();
            }else{
                fout = new FileOutputStream(filepath);
                wb.write(fout);
            }
            fout.close();

            return true;
        } catch (Exception ex) {
           ex.printStackTrace();
            return false;
        } finally {
            try {
                if (fout != null) {
                    fout.close();
                }
            } catch (IOException e) {
              e.printStackTrace();
            }
        }
    }

    private String wrappDesc(Object r, String property) {
        String s = findCodeProperty(property);
        if (s == null) {
            return r.toString();
        } else {
            String desc = systemDictionaryService.getSystemDictionaryDesc(s, r.toString());
            return desc!=null?desc:"";
        }
    }

    private String findCodeProperty(String property){
        if ("wjfl".equals(property)) {
            return "7541";
        }
        if ("dklb".equals(property)) {
            return "7537";
        }
//        if ("cdhdq".equals(property)) {
//            return "19";
//        }
        return null;
    }

}
